<template>
  <div class="history-page">
    <!-- 搜索栏 -->
    <div v-if="!isEmpty" class="search-container">
      <van-search
        v-model="searchKeyword"
        placeholder="搜索历史记录"
        @search="onSearch"
        @clear="onClearSearch"
      />
    </div>

    <!-- 加载状态 -->
    <van-loading v-if="loading" class="loading-container" vertical>
      加载中...
    </van-loading>

    <!-- 空状态 -->
    <van-empty
      v-else-if="isEmpty"
      image="search"
      description="暂无浏览历史"
    />

    <!-- 历史记录列表 -->
    <div v-else class="history-content">
      <!-- 按日期分组显示 -->
      <div
        v-for="(items, date) in groupedHistory"
        :key="date"
        class="history-group"
      >
        <div class="group-header">
          <span class="group-title">{{ date }}</span>
          <span class="group-count">{{ items.length }}条</span>
        </div>

        <van-cell-group>
          <div
            v-for="item in items"
            :key="item.id"
            class="history-item"
            @click="goToNews(item.id)"
          >
            <div class="item-content">
              <!-- 左侧缩略图 -->
              <div class="article-thumbnail">
                <img
                  v-if="item.thumbnail"
                  :src="item.thumbnail"
                  :alt="item.title"
                  @error="onImageError"
                />
                <van-icon v-else name="photo" size="20" />
              </div>

              <!-- 中间内容区域 -->
              <div class="item-main">
                <div class="item-title">{{ item.title }}</div>
                <div class="item-summary">{{ item.summary }}</div>
              </div>

              <!-- 右侧信息区域 -->
              <div class="item-right">
                <div class="visit-time">{{ formatTime(item.visitTime) }}</div>
                <div class="article-meta">
                  <span v-if="item.category" class="category">{{ item.category }}</span>
                  <span v-if="item.section" class="section">{{ item.section }}</span>
                </div>
                <van-button
                  type="danger"
                  size="mini"
                  class="delete-btn"
                  @click.stop="removeHistoryItem(item.id)"
                >
                  删除
                </van-button>
              </div>
            </div>
          </div>
        </van-cell-group>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { useHistoryStore } from '../stores/history'
import { formatTimeShort as formatTime, formatDate, isSameDay } from '../utils/dateUtils'

const router = useRouter()
const historyStore = useHistoryStore()

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')

// 计算属性
const isEmpty = computed(() => historyStore.isEmpty)
const filteredHistory = computed(() => {
  if (!searchKeyword.value.trim()) {
    return historyStore.historyList
  }
  return historyStore.searchHistory(searchKeyword.value)
})

const groupedHistory = computed(() => {
  if (filteredHistory.value.length === 0) {
    return {}
  }

  // 手动实现分组逻辑
  const groups = {}
  const today = new Date()
  const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000)

  filteredHistory.value.forEach(item => {
    const visitDate = new Date(item.visitTime)
    let groupKey = ''

    if (isSameDay(visitDate, today)) {
      groupKey = '今天'
    } else if (isSameDay(visitDate, yesterday)) {
      groupKey = '昨天'
    } else {
      groupKey = formatDate(visitDate)
    }

    if (!groups[groupKey]) {
      groups[groupKey] = []
    }
    groups[groupKey].push(item)
  })

  return groups
})

// 方法

const goToNews = (newsId) => {
  router.push({ name: 'news-detail', params: { id: newsId } })
}

const onSearch = () => {
  // 搜索逻辑已在计算属性中处理
  console.log('搜索关键词:', searchKeyword.value)
}

const onClearSearch = () => {
  searchKeyword.value = ''
}

const removeHistoryItem = (newsId) => {
  const success = historyStore.removeHistory(newsId)
  if (success) {
    showToast('已删除')
  } else {
    showToast('删除失败')
  }
}

// 时间格式化函数已移至 @/utils/dateUtils.js

const onImageError = (event) => {
  // 图片加载失败时隐藏图片
  event.target.style.display = 'none'
}

// 页面加载时的初始化
onMounted(() => {
  // 可以在这里添加一些初始化逻辑
  console.log('历史记录页面已加载，共', historyStore.historyCount, '条记录')
})
</script>

<style scoped>
.history-page {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.search-container {
  background: white;
  padding: 8px 16px;
  border-bottom: 1px solid #ebedf0;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.history-content {
  padding-bottom: 20px;
}

.history-group {
  margin-bottom: 16px;
}

.group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px 8px;
  background: #f7f8fa;
}

.group-title {
  font-size: 14px;
  font-weight: 600;
  color: #323233;
}

.group-count {
  font-size: 12px;
  color: #969799;
}

/* 历史记录项样式 */
.history-item {
  background: white;
  border-bottom: 1px solid #ebedf0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.history-item:hover {
  background-color: #f7f8fa;
}

.history-item:last-child {
  border-bottom: none;
}

.item-content {
  display: flex;
  align-items: flex-start;
  padding: 12px 16px;
  gap: 12px;
}

.article-thumbnail {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  overflow: hidden;
  background: #f7f8fa;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.article-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-main {
  flex: 1;
  min-width: 0;
  margin-right: 8px;
}

.item-title {
  font-size: 15px;
  font-weight: 500;
  line-height: 1.4;
  color: #323233;
  margin-bottom: 4px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-summary {
  font-size: 13px;
  color: #646566;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 6px;
  flex-shrink: 0;
  min-width: 80px;
}

.visit-time {
  font-size: 12px;
  color: #969799;
  white-space: nowrap;
}

.article-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: flex-end;
}

.category {
  font-size: 11px;
  color: #1989fa;
  background: #e8f3ff;
  padding: 2px 6px;
  border-radius: 8px;
  white-space: nowrap;
}

.section {
  font-size: 11px;
  color: #ff976a;
  background: #fff7f0;
  padding: 2px 6px;
  border-radius: 8px;
  white-space: nowrap;
}

.delete-btn {
  margin-top: 4px;
}

/* 响应式设计 */
@media (max-width: 375px) {
  .item-content {
    padding: 10px 12px;
    gap: 10px;
  }

  .article-thumbnail {
    width: 36px;
    height: 36px;
  }

  .item-title {
    font-size: 14px;
  }

  .item-summary {
    font-size: 12px;
  }

  .item-right {
    min-width: 70px;
  }

  .visit-time {
    font-size: 11px;
  }

  .category,
  .section {
    font-size: 10px;
    padding: 1px 4px;
  }
}
</style>
